package minaClient;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Random;
import java.util.Scanner;

/**
 * Created by kz on 2017/5/1.
 */
public class minaclient {

    private SocketConnector connector;
    private ConnectFuture future;
    public static IoSession session;

    private static  class inputThread extends Thread {
        inputThread(String name) {
            super(name);//调用父类带参数的构造方法
        }

        public void run() {
            while (true) {
                Scanner scanner = new Scanner(System.in);
                System.out.println("请输入字符串");
                String result = scanner.next();

                if (result.trim().equals("1")) {       //如果输入1,则动作
                    session.write("1");
                    System.out.println("OK了");
                }

                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    System.out.println("thread sleep错误");
                }
            }
        }
    }

    public boolean connect() {
        /*
         * 1.创建一个socket连接,连接到服务器
         */
        connector = new NioSocketConnector();

        /*
         * 获取过滤器链,用于添加过滤器
         */
        DefaultIoFilterChainBuilder chain = connector.getFilterChain();

        // b.添加日志过滤器
        chain.addLast("logger", new LoggingFilter());

        // c.添加字符的编码过滤器
        chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));

        /*
         * 3.设置消息处理器，用于处理接收到的消息
         */
        connector.setHandler(new MsgHanler());

        /*
         * 4.根据IP和端口号连接到服务器
         */
        future = connector.connect(new InetSocketAddress("127.0.0.1", 8888));
        // 等待连接创建完成
        future.awaitUninterruptibly();

        /*
         * 5.获取session对象,通过session可以向服务器发送消息；
         */
        session = future.getSession();
        session.getConfig().setUseReadOperation(true);
        if(session.isConnected()){
            System.out.println("已经连接");
        }
        else{
            System.out.println("连接失败");
        }
        return future.isConnected();
    }

    /**
     * 往服务器发送消息
     *
     * @param message
     */
    public void sendMsg2Server(String message) {
        session.write(message);
    }

    /**
     * 关闭与服务器的连接
     *
     * @return
     */
    public boolean close() {
        CloseFuture future = session.getCloseFuture();
        future.awaitUninterruptibly(1000);
        connector.dispose();
        return true;
    }

    public static void main(String[] args) {
        String  sendatas = "test1";
        final String   ss = "aaaaaaasss";
        minaclient client = new minaclient();
        client.connect();
        inputThread theinputThread = new inputThread("test");
        theinputThread.start();
        for (int i = 0; i < 180; i++) {
            sendatas += ss;
        }

        while (true) {

//            client.sendMsg2Server("message from cilent:random  = ");
            client.sendMsg2Server(sendatas);
            try {

                Thread.sleep(1000);
            } catch (Exception e) {
                client.close();
            }

        }

    }
}
